package com.wn.manpower.web;

import com.wn.common.PageBean;
import com.wn.common.ResponseEntity;
import com.wn.entity.ChangePosts;
import com.wn.entity.Hr;
import com.wn.entity.Recipients;
import com.wn.manpower.service.HumanResourcesService;
import com.wn.manpower.service.RecipientsService;
import com.wn.manpower.vo.DimissionVo;
import com.wn.manpower.vo.RecipientsVo;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 办公领用
 * @author dzj
 * date: 2022/10/20
 */
@Slf4j
@RestController
@RequestMapping("/manpower/recipients")
public class RecipientsController {

    @Autowired
    private RecipientsService recipientsService;

    @Autowired
    private HumanResourcesService humanResourcesService;

    @RequestMapping("/add")
    public ResponseEntity add(@RequestBody RecipientsVo recipientsVo, HttpServletRequest request) {
            ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
            RuntimeService runtimeService = processEngine.getRuntimeService();
            String key = "recipients";

//       创建变量集合
            Map<String, Object> map1 = new HashMap<>();
//      设置user1的取值，用户可以在界面上设置流程的执行  申请人
            map1.put("user1", recipientsVo.getUser1());
            //下一个任务负责人
            Map<String, Object> map2 = new HashMap<>();
            map2.put("user2", recipientsVo.getUser2());
//        启动流程实例，并设置流程变量的值（把map1传入）
            ProcessInstance processInstance =
                    runtimeService.startProcessInstanceByKey(key, map1);

            //通过界面传输的id获得hr实例，得知其名字
            int userId = Integer.parseInt(request.getHeader("userId"));
            Hr hr = humanResourcesService.getById(userId);
//        获取taskService  实例申请同时完成第一步
            TaskService taskService = processEngine.getTaskService();
            Task task = taskService.createTaskQuery()
                    .processDefinitionKey(key) //流程Key
                    .taskAssignee(hr.getWorkNumber())  //要查询的负责人
                    .singleResult();
            //完成任务的时候设置下一个负责人  前端记得传输负责人
            taskService.complete(task.getId(), map2);
            log.debug("申请执行完成", "下一负责人" + recipientsVo.getUser2());

            //查询下一个负责人任务
            List<Task> tasks = taskService.createTaskQuery()
                    .processDefinitionKey(key) //流程Key
                    .taskAssignee(recipientsVo.getUser2())//只查询该任务负责人的任务
                    .list();

            //处理完成后 查询出当前任务id加入到数据库表格
            recipientsVo.getRecipients().setActivitiInstanceId(tasks.get(0).getId());
            recipientsService.add(recipientsVo.getRecipients());

            return ResponseEntity.success;

    }

    /**
     * 查询当前个人待执行的任务,就是点击页面，直接展示自己的任务
     *
     * 通过用户id，获得当前用户的任务id
     * 通过任务id，多条件查询表格
     */
    @RequestMapping("/getTask")
    public ResponseEntity getTask(HttpServletRequest request) {
        String key = "recipients";
        //通过界面传输的id获得hr实例，得知其名字
        int userId = Integer.parseInt(request.getHeader("userId"));
        Hr hr = humanResourcesService.getById(userId);

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        List<Task> tasks = taskService.createTaskQuery()
                .processDefinitionKey(key) //流程Key
                .taskAssignee(hr.getName())//只查询该任务负责人的任务
                .list();

        List<Recipients> recipientsList = null;

        for (int i = 0; i < tasks.size(); i++) {
            //通过任务id查询数据
            Recipients recipients = recipientsService.getByActivitiInstanceId(tasks.get(i).getId());
            recipientsList.add(recipients);
        }

        return new ResponseEntity(recipientsList);
    }

    /**
     * 完成任务
     */
    @RequestMapping("/down")
    public ResponseEntity down(@RequestBody RecipientsVo recipientsVo) {
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();

        Map<String, Object> map = new HashMap<>();
        map.put("user2", recipientsVo.getUser2());

        String key = "recipients";

//        完成任务,参数：任务id
        taskService.complete(recipientsVo.getRecipients().getActivitiInstanceId(), map);

        recipientsVo.getRecipients().setActivitiInstanceId("完成");
        recipientsService.update(recipientsVo.getRecipients());

        return ResponseEntity.success;
    }



    @RequestMapping("/update")
    public ResponseEntity update(@RequestBody Recipients recipients) {
        recipientsService.update(recipients);
        return ResponseEntity.success;
    }

    @RequestMapping("/getById/{id}")
    public ResponseEntity getById(@PathVariable int id) {
        Recipients recipients = recipientsService.getById(id);
        return new ResponseEntity(recipients);
    }

    @RequestMapping("/getPageByCondition")
    public ResponseEntity getByCondition(@RequestBody RecipientsVo recipientsVo) {
        PageBean<Recipients> pageBean = recipientsService.getPageByCondition(recipientsVo.getRecipients(), recipientsVo.getCurrPage(), recipientsVo.getPageSize());
        return new ResponseEntity(pageBean);
    }

    @RequestMapping("/del/{id}")
    public ResponseEntity del(@PathVariable int id) {
        recipientsService.del(id);
        return ResponseEntity.success;
    }
}
